// server/controllers/fileController.js
const fs = require('fs')
const path = require('path')
const { hasDuplicateGroups } = require('../utils/fileUtils')

const BASE_DIR = path.join(__dirname, '../data')

// 创建文件
exports.createFile = (req, res) => {
  const { folder, date } = req.params
  const folderPath = path.join(BASE_DIR, folder)

  // 确保目录存在
  if (!fs.existsSync(folderPath)) {
    fs.mkdirSync(folderPath, { recursive: true })
  }

  try {
    const data = req.body

    // 获取当前目录下所有文件的历史数据
    const historicalData = fs
      .readdirSync(folderPath)
      .filter((file) => file.endsWith('.json'))
      .flatMap((file) => {
        const content = JSON.parse(fs.readFileSync(path.join(folderPath, file), 'utf-8'))
        return Object.values(content).flat()
      })

    // 检查是否存在重复数据
    if (hasDuplicateGroups(data, historicalData)) {
      return res.status(400).json({
        success: false,
        message: '保存失败: 数据包含重复的子数组！'
      })
    }

    // 生成唯一文件名
    const existingFiles = fs.readdirSync(folderPath).filter((file) => file.startsWith(date) && file.endsWith('.json'))
    let nextFileIndex = 1
    if (existingFiles.length > 0) {
      const lastFile = existingFiles.sort()[existingFiles.length - 1]
      const match = lastFile.match(/-(\d+)\.json$/)
      if (match) {
        nextFileIndex = parseInt(match[1]) + 1
      }
    }
    const fileName = `${date}-${nextFileIndex}.json`
    const filePath = path.join(folderPath, fileName)

    // 写入文件
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8')
    res.json({ success: true, message: `文件已成功保存为 ${fileName}` })
  } catch (error) {
    console.error('写入文件失败:', error)
    res.status(500).json({ success: false, message: '写入文件失败' })
  }
}

// 获取文件数据
exports.getFile = (req, res) => {
  const { folder, file } = req.params
  const filePath = path.join(BASE_DIR, folder, file)

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ success: false, message: '文件不存在' })
  }

  try {
    const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    res.json({ success: true, data })
  } catch (error) {
    res.status(500).json({ success: false, message: '读取文件失败' })
  }
}

// 删除文件
exports.deleteFile = (req, res) => {
  const { folder, file } = req.params
  const filePath = path.join(BASE_DIR, folder, file)

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ success: false, message: '文件不存在' })
  }

  try {
    fs.unlinkSync(filePath)
    res.json({ success: true, message: `文件 ${file} 已成功删除` })
  } catch (error) {
    res.status(500).json({ success: false, message: '删除文件失败' })
  }
}
